package com.gao.shiro.demo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author gaofeng
 * @date 2022年06月29日 23:22
 */
//@Configuration
public class ShiroConfig {


    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean() ;
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 设置过滤器,拦截
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        /*
          anon：无需认证就能访问
          authc：必须认证才能访问
          user：必须拥有 记住我 功能才能使用
          perms：拥有对某个资源的权限才能访问
          role：拥有某个角色权限才能访问
         */
        filterChainDefinitionMap.put("/user/add", "authc") ;
        filterChainDefinitionMap.put("/user/update", "authc") ;
        //        filterChainDefinitionMap.put("/user/*", "authc") ;

        filterChainDefinitionMap.put("/user/add", "perms[user:add]") ;
        filterChainDefinitionMap.put("/user/update", "perms[user:update]") ;

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        // 登录请求
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        // 未授权跳转
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorize");
        return shiroFilterFactoryBean ;
    }

    /**
     * 2. 创建DefaultWebSecurityManager对象
     *
     * @return org.apache.shiro.web.mgt.DefaultWebSecurityManager
     */
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager ;
    }

    /**
     * 1. 获取Realm对象
     *
     * @return com.gao.shiro.demo.config.UserRealm
     */
    @Bean(name = "userRealm")
    public UserRealm getUserRealm() {
        return new UserRealm();
    }
}
